#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from optparse import OptionParser
from plane import Plane

def line_parse(line):    
    line = line.expandtabs(1)
    line = [x for x in line.split(' ') if x != '' ]    
    # the format of the string to parse is
    # DIR DIP LINE "TR" looks col,col,col
    DIP, DIR 
    try:
        DIR, DIP = int(line.pop(0)), int(line.pop(0))
    except:
        if line != []:
            sys.stderr.write('WARNING! Cannot parse string: %s\n' % line)
        return None    
    return DIR, DIP

def compare(maxs1, maxs2):
    if len(maxs1)<len(maxs2):
        maxsa , maxsb = maxs1, maxs2
    else:
        maxsa , maxsb = maxs2, maxs1
    angles=[]
    for max in maxsa:
        angles_cur = []
        plane_a = Plane(max[0],max[1])
        for omax in maxsb:
            plane_b = Plane(omax[0],omax[1])
            angle = plane_a.normal().return_angle_between(plane_b.normal())   
            angles_cur.append(angle**2)
        angles.append(min(angles_cur))
    sum = 0
    for angle in angles:
        sum+=angle
    return sum


args = sys.argv[a:]
maxs = []
for max in args:
    name = max[:-4]
    # get data from file of name
    f = open(max, 'r')
    lines = f.readlines(); f.close()
    data=[name]
    for line in lines:
        val = line_parse(line)
        if val != None: data.append(val)  
    maxs.append(data)
'''
maxs = [["NG01", [035, 45], [216, 84]],
        ["NG02", [035, 53], [210, 80], [120, 12]],
        ["NG03", [012, 34], [67, 19], [90, 34], [155, 54], [212, 72]]]
'''
matrix = [[site[0] for site in maxs]]
for i in range(len(maxs)):
    matrix_cur = []
    for j in range(len(maxs)):
        matrix_cur.append(compare(maxs[i][1:],maxs[j][1:]))
    matrix.append(matrix_cur)
for max in matrix:
    print max
